import axios from 'axios'
//导入进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// http request 拦截器
axios.interceptors.request.use(
  config => {
    NProgress.start()
    // 设置参数格式
    if (!config.headers['Content-Type']) {
      config.headers = {'Content-Type': 'application/json'}
    }
    // 添加token到headers
    let token = window.sessionStorage.getItem('token')
    config.headers.Authorization = token
    // config.headers.Authorization = window.sessionStorage.getItem('token')
    // console.log("request token", token);


    // 鉴权参数设置
    if (config.method === 'get') {
      // get请求下 参数在params中，其他请求在data中
      config.params = config.params || {}
      // let url = config.url
      // url.indexOf('?') === -1 ? config.url = url + '?_=' + (new Date().getTime()) : config.url = url + '&_=' + (new Date().getTime())
      // 一些参数处理
    } else {
      config.data = config.data || {}
      // 一些参数处理
    }
    return config
  },
  err => {
    return Promise.reject(err)
    // 一些参数处理
  }
)
// // // http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log("response拦截器", response)
    console.log("返回status:", response.data.meta.status)
    NProgress.done()
    if (response.data.meta.status === 200) {
      // console.log(response.data.data.token);
      // 登录验证
      // 做了个示例跳转项目中登录，并记录下相对路径
      // router.push({
      //   name: 'login',
      //   query: {
      //     retUrl: window.location.href.split('#')[1] || '',
      //     is_new_user_url: 1
      //   }
      // })

    }
    return response
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise<unknown>}
 */
export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(response => {
      resolve(response.data)
    }).catch(
      err => {
        reject(err)
        let message = '请求失败！请检查网络'
        // 错误处理
        if (err.response)
          message = err.response.data.message
        console.log(message)
      }
    )
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
export function post(url, data = {}) {
  // console.log("data=", data);
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(response => {
      resolve(response.data)
    }), err => {
      reject(err)
      // 错误处理
      let message = '请求失败！请检查网络'
      if (err.response)
        message = err.response.data.message
      console.log(message)
    }
  })
}

/**
 *封装patch请求
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
        let message = '请求失败！请检查网络'
        if (err.response) message = err.response.data.message
        console.log(message)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
        let message = '请求失败！请检查网络'
        if (err.response) message = err.response.data.message
        console.log(message)
      })
  })
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
export function del(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
        let message = '请求失败！请检查网络'
        if (err.response) message = err.response.data.message
        console.log(message)
      })
  })
}

//格式化参数
export function parseParam(data) {
  try {
    let tempArr = []
    for (let i in data) {
      let key = encodeURIComponent(i)
      let value = encodeURIComponent(data[i])
      tempArr.push(key + '=' + value)
    }
    let urlParamsStr = tempArr.join('&')
    return urlParamsStr
  } catch (err) {
    return ''
  }
}

